package leetcode;

/**
 * @author Liangyaoyun
 */
public class leetCode67 {
    //拓展知识
/*    public String addBinary(String a, String b) {
        return Integer.toBinaryString(
                Integer.parseInt(a, 2) + Integer.parseInt(b, 2)
        );
    }*/
    public String addBinary(String a, String b) {
        StringBuilder res=new StringBuilder();
        //进位
        int carry=0;
        for (int i = a.length()-1,j=b.length()-1; i >=0||j>=0 ; i--,j--) {
            int sum=carry;
            //较短的那个字符串前面自动补0
            sum+=i>=0?a.charAt(i)-'0':0;
            sum+=j>=0?b.charAt(j)-'0':0;
            res.append(sum%2);
            carry=sum/2;
        }
        //如果进位等于1则说明前面需要加一个1,反之则是0
        res.append(carry==1?carry:"");
        //需要将答案反转
        return res.reverse().toString();
    }
}

